package org.e_gold.service.impl;

import java.util.Map;

import org.e_gold.dao.CookieDAO;
import org.e_gold.dto.Cookies;
import org.e_gold.model.Cookie;
import org.e_gold.service.CookieService;
import org.e_gold.util.BrowserTypeENUM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CookieServiceImpl implements CookieService {

	@Autowired
	private CookieDAO cookieDAO;

	@Override
	public void saveCookies(Cookies cookies) {

		saveCookies(cookies, null);

	}

	private void saveCookies(Cookies cookies, String browserType) {

		if (cookies.getCookieMap() != null) {
			for (Map.Entry<String, String> entry : cookies.getCookieMap().entrySet()) {
				Cookie c = cookieDAO.findCookieByName(entry.getKey());
				if (c == null) {
					c = new Cookie();
					c.setName(entry.getKey());
					c.setValue(entry.getValue());
					c.setBrowserType(browserType == null ? BrowserTypeENUM.FIREFOX_VERSION.toString() : browserType);
					cookieDAO.insert(c);
				} else {
					c.setBrowserType(browserType == null ? BrowserTypeENUM.FIREFOX_VERSION.toString() : browserType);
					c.setValue(entry.getValue());
					cookieDAO.update(c);
				}
			}
		}
	}

}
